﻿using SmartDevice.Library.Device.Power;
using SmartDevice.Library.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XY.Communication;
using PowerStatus = SmartDevice.Library.Device.Power.PowerStatus;

namespace SmartDevice.PowerSimulator
{
    public partial class FormMain : Form
    {
        private UDPClient MyUDPClient = null;
        private IPEndPoint deviceIPEndPoint = null;

        private PowerStatus PowerStatus = PowerStatus.OFF;
        private float Voltage = 0;
        private float Current = 0;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            this.lblVoltage.Text = "Power OFF";
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string LocalIP = this.txtLocalIP.Text;
            int LocalPort = (int)this.numLocalPort.Value;
            string DeviceIP = this.txtDeviceIP.Text;
            int DevicePort = (int)this.numDevicePort.Value;

            deviceIPEndPoint = new IPEndPoint(IPAddress.Parse(LocalIP), LocalPort);
            MyUDPClient = new UDPClient(DeviceIP, DevicePort);
            MyUDPClient.UDPMessageReceived += MyUDPClient_UDPMessageReceived;

            this.btnConnect.Enabled = false;
            this.btnDisconnect.Enabled = true;
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            MyUDPClient?.CloseUDP();
            MyUDPClient = null;

            this.btnConnect.Enabled = true;
            this.btnDisconnect.Enabled = false;
        }

        private void MyUDPClient_UDPMessageReceived(UdpStateEventArgs args)
        {
            var buffer = args.buffer;
            var bytes = buffer.Length;

            //写日志
            this.Invoke(new Action(() =>
            {
                var hexstr = ConvertHelper.ByteArrayToHexString(buffer);
                txtLog.Text += $"\r\n[{DateTime.Now:HH:mm:ss}] -> {hexstr}";

                this.txtLog.SelectionStart = this.txtLog.Text.Length + 10;
                this.txtLog.SelectionLength = 0;
                this.txtLog.ScrollToCaret();
            }));

            //响应协议 01 03 03 00 F1 28 
            if (bytes == 6 && buffer[0] == 0x01 && buffer[1] == 0x03 && buffer[2] == 0x03 && buffer[3] == 0x00)
            {
                // 01 03 03 06 S1 S2 V_Hi V_Low Cur_Hi Cur_Low CRC_Hi CRC_Low
                byte[] senddata = new byte[12] { 0x01, 0x03, 0x03, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

                senddata[4] = senddata[5] = (byte)(PowerStatus == PowerStatus.ON ? 0xFF : 0x00);

                ushort Vo = (ushort)(Voltage * 10);
                byte[] V = BitConverter.GetBytes(Vo);
                senddata[6] = V[1];
                senddata[7] = V[0];

                byte[] C = BitConverter.GetBytes((ushort)(Current * 10));
                senddata[8] = C[1];
                senddata[9] = C[0];

                senddata = CRC.CalCRC16a(senddata);
                MyUDPClient.SendData(deviceIPEndPoint,senddata);

                //写日志
                this.Invoke(new Action(() =>
                {
                    var hexstr = ConvertHelper.ByteArrayToHexString(senddata);
                    txtLog.Text += $"\r\n[{DateTime.Now:HH:mm:ss}] <- {hexstr}";
                }));
            }

            //Power OFF :01 01 03 00 00 E8 3C
            if (bytes == 7 && buffer[0] == 0x01 && buffer[1] == 0x01 && buffer[2] == 0x03 && buffer[3] == 0x00 && buffer[4] == 0x00)
            {
                PowerStatus = PowerStatus.OFF;
                Voltage = Current = 0;

                this.Invoke(new Action(() =>
                {
                    this.lblVoltage.Text = "Power OFF";
                }));
            }

            //PowerON:01 01 03 FF FF V_Hi V_Low Cur_Hi Cur_Low CRC_Hi CRC_Low
            if (bytes == 11 && buffer[0] == 0x01 && buffer[1] == 0x01 && buffer[2] == 0x03 && buffer[3] == 0xFF && buffer[4] == 0xFF)
            {
                PowerStatus = PowerStatus.ON;
                Voltage = (float)BitConverter.ToUInt16(new byte[] { buffer[6], buffer[5] }, 0) / 10;
                Current = (float)BitConverter.ToUInt16(new byte[] { buffer[8], buffer[7] }, 0) / 10;

                this.Invoke(new Action(() =>
                {
                    this.lblVoltage.Text = $"DC {Voltage:000.0} V";
                }));
            }
        }

        private void linkClear_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtLog.Text = "";
        }
    }
}
